package com.alisls.demo.springcloud.common.web.advice;

import com.alisls.demo.springcloud.common.core.exception.BizException;
import com.alisls.demo.springcloud.common.model.dto.DefaultResult;
import com.alisls.demo.springcloud.common.model.dto.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.TypeMismatchException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 通用异常处理
 *
 * @author Ke Wang
 */
@Log4j2
public class BaseAdvice {

    /**
     * 捕获TypeMismatchException异常
     * @param typeMismatchException
     * @return Result
     */
    @ExceptionHandler(TypeMismatchException.class)
    public Result argumentTypeMismatchException(TypeMismatchException typeMismatchException) {
        String message = "参数类型不匹配错误！" + typeMismatchException.getMessage();
        log.error(message);
        return DefaultResult.ofFail(message);
    }

    /**
     * 捕获MethodArgumentNotValidException异常
     * Hibernate-Validator校验框架抛出的异常
     * @param methodArgumentNotValidException 方法参数异常类
     * @return Result
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException) {
        String message = "方法参数不合法错误：" + methodArgumentNotValidException.getMessage();
        log.error(message);
        return DefaultResult.ofFail(message);
    }

    /**
     * 捕获BizException异常
     * @param bizException 业务逻辑异常
     * @return Result
     */
    @ExceptionHandler(BizException.class)
    public Result bizException(BizException bizException) {
        String message = bizException.getMessage();
        log.error(message);
        return DefaultResult.ofFail(message);
    }

    /**
     * 捕获所有异常
     * @param e 异常
     * @return Result
     */
    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        String message = "程序出现未知的错误：" + e.getMessage();
        log.error(message);
        e.printStackTrace();
        return DefaultResult.ofFail(message);
    }
	
}
